package com.yenlien.traceyun.plant.controller;

import com.yenlien.traceyun.business.interceptor.PassToken;
import com.yenlien.traceyun.plant.dao.ExchangesDao;
import com.yenlien.traceyun.plant.entity.Exchanges;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author ChenXi
 * @date 2023/6/19
 */
@Slf4j
@RestController
@RequestMapping("/trading")
public class TradingCenterController {

    @Autowired
    private ExchangesDao exchangesDao;

    /**
     * 交易大屏其他数据
     *
     * @return
     */
    @PassToken
    @GetMapping("/getDate")
    public Object getDate() {
        return getTimingData();
    }

    /**
     * 商品价格走势每月值
     *
     * @return
     */
    @PassToken
    @GetMapping("/getYumi")
    public Object getYumi() {
        return getTimingMonth();
    }

    private Map<String, Object> getTimingData() {
        List<Exchanges> exchanges = exchangesDao.findAll();
        //生产企业
        List<Exchanges> collect = exchanges.stream().filter(x -> x.getInventoryFirm() != null).collect(Collectors.toList());
        //交易成交实况
        List<Exchanges> collect1 = exchanges.stream().filter(x -> x.getMarketnum() != 0).collect(Collectors.toList());
        //热销排行
        List<Exchanges> collect2 = exchanges.stream().filter(e -> e.getHotProduct() != null)
                .sorted(Comparator.comparing(Exchanges::getHotProductNum, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        //热销产品前三
        List<Exchanges> collect3 = collect2.stream().limit(3).collect(Collectors.toList());
        //库存实况
        List<Exchanges> collect4 = exchanges.stream().filter(x -> x.getKind() != null).collect(Collectors.toList());

        //中间旋转总数据统计
        //总销售商品数量
        int marketSum = exchanges.stream().mapToInt(e -> e.getMarketSum()).sum();
        //热销总金额
        int moneySum = exchanges.stream().mapToInt(e -> (int) e.getMarketmoney()).sum();
        BigDecimal bd = new BigDecimal(moneySum);
        double output = bd.divide(new BigDecimal(10000), 1, RoundingMode.HALF_UP).doubleValue();
        DecimalFormat df = new DecimalFormat("#0.0");
        String result = df.format(output) + "万";
        //销售库存占比
        int stockSum = exchanges.stream().mapToInt(e -> e.getStockNum()).sum();
        double percent = (double) Math.min(marketSum, stockSum) / Math.max(marketSum, stockSum) * 100;
        DecimalFormat format = new DecimalFormat("0.0");

        //商品价格走势
        List<Exchanges> collect5 = exchanges.stream().filter(x -> x.getStockNum() != 0).collect(Collectors.toList());
        //构建月份排行
        List<Exchanges> collect6 = exchanges.stream().filter(x -> x.getMonth() != 0).collect(Collectors.toList());

        //商品价格走势占比
        Map<String, Object> map1 = new HashMap<>();
        List<Map<String, Object>> collect7 = exchanges.stream().filter(e -> e.getKind() != null).map(x -> {
            String kind = x.getKind();
            switch (kind) {
                case "新牦牛肉":
                    extracteMoney(x, moneySum, map1, "XMNR");
                    break;
                case "牦牛肉干":
                    extracteMoney(x, moneySum, map1, "MNRG");
                    break;
                case "工艺品":
                    extracteMoney(x, moneySum, map1, "GYP");
                    break;
                case "农特产":
                    extracteMoney(x, moneySum, map1, "NTC");
                    break;
            }
            return map1;
        }).collect(Collectors.toList());

        Map<String, Object> map = new LinkedHashMap<>();
        map.put("SCQY", collect);  //生产企业
        map.put("JYCJSK", collect1);  //交易成交实况
        map.put("RXPH", collect2);  //热销排行
        map.put("RXCPQS", collect3);  //热销产品前三
        map.put("KCSK", collect4);  //库存实况
        map.put("XSSP", marketSum);
        map.put("RXJE", result);
        map.put("XSKC", format.format(percent) + "%");
        map.put("SPJGZB", collect7.get(0));
        return map;
    }

    /**
     * 判断百分比
     *
     * @param x
     * @param moneySum
     * @param map1
     * @param XMNR
     */
    private void extracteMoney(Exchanges x, int moneySum, Map<String, Object> map1, String XMNR) {
        int percentage = (int) ((x.getMarketmoney() / moneySum) * 100);
        map1.put(XMNR, percentage + "%");
    }

    /**
     * 每隔24小时定时添加数据到数据库
     */
    @Scheduled(cron = "0 0 0/24 * * ?")
    public void addData() {
        log.info(new SimpleDateFormat("yyyy-MM-dd HH:mm").format(new Date()) + "执行定时任务");
        List<Exchanges> exchanges = exchangesDao.findAll();
        //生产企业
        List<Exchanges> collect = exchanges.stream().filter(x -> x.getInventoryFirm() != null).map(e -> {
            int i = e.getInventory() + 2;
            e.setInventory(i);
            return e;
        }).collect(Collectors.toList());
        //交易成交实况
        // 获取当前日期时间的 Calendar 对象
        Calendar calendar = Calendar.getInstance();
        // 将日期时间往前推一天
        calendar.add(Calendar.DATE, -1);
        // 获取当前日期时间的 Calendar 对象
        Calendar calendar1 = Calendar.getInstance();
        // 将日期时间往前推一天
        calendar1.add(Calendar.DATE, -2);
        List<Exchanges> collect1 = exchanges.stream().filter(x -> x.getMarketnum() != 0).map(e -> {
            if (e.getProductName().equals("岭惠源牦牛肉干")) {
                e.setOrderTime(new SimpleDateFormat("yyyy-MM-dd").format(new Date()));
                int marketnum = e.getMarketnum() + 2;
                double marketmoney = e.getMarketmoney() + 176;
                e.setMarketnum(marketnum);
                e.setMarketmoney(marketmoney);
            } else if (e.getProductName().equals("甘孜德格虫草特产")) {
                e.setOrderTime(new SimpleDateFormat("yyyy-MM-dd").format(calendar.getTime()));
                int marketnum1 = e.getMarketnum() + 2;
                double marketmoney1 = e.getMarketmoney() + 238;
                e.setMarketnum(marketnum1);
                e.setMarketmoney(marketmoney1);
            } else if (e.getProductName().equals("高原人参果")) {
                e.setOrderTime(new SimpleDateFormat("yyyy-MM-dd").format(calendar1.getTime()));
                int marketnum2 = e.getMarketnum() + 2;
                double marketmoney2 = e.getMarketmoney() + 42;
                e.setMarketnum(marketnum2);
                e.setMarketmoney(marketmoney2);
            }
            return e;
        }).collect(Collectors.toList());
        //热销排行
        List<Exchanges> collect2 = exchanges.stream().filter(e -> e.getHotProduct() != null)
                .map(e -> {
                    int i = e.getHotProductNum() + 2;
                    e.setHotProductNum(i);
                    return e;
                })
                .sorted(Comparator.comparing(Exchanges::getHotProductNum, Comparator.reverseOrder()))
                .collect(Collectors.toList());
        //库存实况
        List<Exchanges> collect4 = exchanges.stream().filter(x -> x.getKind() != null).map(d -> {
            if (d.getKind().equals("牦牛肉干")) {
                int i = d.getStockNum() - 4;
                int i1 = d.getMarketSum() + 4;
                double i2 = d.getMarketmoney() + 1308;
                d.setStockNum(i);
                d.setMarketSum(i1);
                d.setMarketmoney(i2);
            } else if (d.getKind().equals("农特产")) {
                int i = d.getStockNum() - 18;
                int i1 = d.getMarketSum() + 18;
                double i2 = d.getMarketmoney() + 2080;
                d.setStockNum(i);
                d.setMarketSum(i1);
                d.setMarketmoney(i2);
            } else if (d.getKind().equals("新牦牛肉")) {
                int i = d.getStockNum() - 8;
                int i1 = d.getMarketSum() + 8;
                double i2 = d.getMarketmoney() + 1960;
                d.setStockNum(i);
                d.setMarketSum(i1);
                d.setMarketmoney(i2);
            } else if (d.getKind().equals("工艺品")) {
                int i = d.getStockNum() - 16;
                int i1 = d.getMarketSum() + 16;
                double i2 = d.getMarketmoney() + 2260;
                d.setStockNum(i);
                d.setMarketSum(i1);
                d.setMarketmoney(i2);
            }
            return d;
        }).collect(Collectors.toList());
        //构建月份排行
        List<Exchanges> collect6 = exchanges.stream().filter(x -> x.getMonth() != 0).map(e -> {
            e.setMonth(e.getMonth() + 100);
            return e;
        }).collect(Collectors.toList());
        ArrayList<Exchanges> list = new ArrayList<>();
        list.addAll(collect);
        list.addAll(collect1);
        list.addAll(collect2);
        list.addAll(collect4);
        list.addAll(collect6);
        exchangesDao.saveAll(list);
//        updateAll(collect, collect1, collect2, collect4, collect6);
    }

    private List<LinkedHashMap<String, Object>> getTimingMonth() {
        List<Exchanges> exchanges = exchangesDao.findAll();
        //构建月份排行
        LinkedHashMap<String, Object> map = new LinkedHashMap<>();
        LinkedHashMap<String, Object> map1 = new LinkedHashMap<>();
        LinkedHashMap<String, Object> map2 = new LinkedHashMap<>();
        LinkedHashMap<String, Object> map3 = new LinkedHashMap<>();
        List<Exchanges> collect1 = exchanges.stream().filter(x -> x.getMonth() != 0).collect(Collectors.toList());
        for (Exchanges ex : collect1) {
            if (ex.getKind().equals("新牦牛肉")) {
                int month = ex.getMonth();
                map = getMap(map, ex.getKind(), month);
            } else if (ex.getKind().equals("牦牛肉干")) {
                int month = ex.getMonth();
                map1 = getMap(map1, ex.getKind(), month);
            } else if (ex.getKind().equals("工艺品")) {
                int month = ex.getMonth();
                map2 = getMap(map2, ex.getKind(), month);
            } else if (ex.getKind().equals("农特产")) {
                int month = ex.getMonth();
                map3 = getMap(map3, ex.getKind(), month);
            }
        }
        List<LinkedHashMap<String, Object>> list = new ArrayList<>();
        list.add(map);
        list.add(map1);
        list.add(map2);
        list.add(map3);

        return list;
    }

    private LinkedHashMap<String, Object> getMap(LinkedHashMap<String, Object> hashMap, String kind, int month) {
        hashMap.put("kind", kind);
        hashMap.put("one", month);
        hashMap.put("two", month + 100);
        hashMap.put("three", month + 150);
        hashMap.put("four", month + 200);
        hashMap.put("five", month + 250);
        hashMap.put("six", month + 300);
        return hashMap;
    }

    private void updateAll(List<Exchanges> collect, List<Exchanges> collect1, List<Exchanges> collect2, List<Exchanges> collect4, List<Exchanges> collect6) {
        try {

            exchangesDao.saveAll(collect);
            for (Exchanges exchanges1 : collect1) {
                exchangesDao.save(exchanges1);
            }
            for (Exchanges exchanges1 : collect2) {
                exchangesDao.save(exchanges1);
            }
//            for (Exchanges exchanges1 : collect3) {
//                exchangesDao.save(exchanges1);
//            }
            for (Exchanges exchanges1 : collect4) {
                exchangesDao.save(exchanges1);
            }
//            for (Exchanges exchanges1 : collect5) {
//                exchangesDao.save(exchanges1);
//            }
            for (Exchanges exchanges1 : collect6) {
                exchangesDao.save(exchanges1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
